package cn.tedu._05mvcboot03.common.exception;

import cn.tedu._05mvcboot03.common.response.JsonResult;
import cn.tedu._05mvcboot03.common.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult dohandleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        log.debug("处理参数校验失败异常：{}",e.getMessage());
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return new JsonResult(StatusCode.VALIDATED_ERROR,message);
    }

    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException e){
        log.debug("处理参数校验失败异常：{}",e.getMessage());
        String message = e.getConstraintViolations().iterator().next().getMessage();
        return new JsonResult(StatusCode.VALIDATED_ERROR,message);
    }

}
